﻿using System;
using System.Diagnostics;

namespace PlayTrace
{
    static class TestTraceSwitch
    {
        private static void Print(this TraceSwitch traceSwitch, TraceLevel level, string message)
        {
            Trace.WriteLineIf(level <= traceSwitch.Level, string.Format("[{0}]: {1}", traceSwitch.DisplayName, message));
        }

        private static void Print(this BooleanSwitch boolSwitch, TraceLevel level, string message)
        {
            Trace.WriteLineIf(boolSwitch.Enabled, string.Format("<{0}>: {1}", boolSwitch.DisplayName, message));
        }

        private static void CheckTraceSwitch(Func<TraceSwitch> traceSwitchFactory)
        {
            Trace.Listeners.Clear();
            Trace.Listeners.Add(new ConsoleTraceListener());
            Trace.Listeners.Add(new TextWriterTraceListener("TestTraceSwitch.log"));

            TraceSwitch traceSwitch = traceSwitchFactory();

            traceSwitch.Print(TraceLevel.Info, "information");
            traceSwitch.Print(TraceLevel.Warning, "warning");
            traceSwitch.Print(TraceLevel.Error, "error");
            traceSwitch.Print(TraceLevel.Info, "*******************************************");
            Trace.Flush();// must Flush, otherwise, messages won't dump into the file
        }

        private static void CheckBoolSwitch(Func<BooleanSwitch> boolswitchFactory)
        {
            Trace.Listeners.Clear();
            Trace.Listeners.Add(new ConsoleTraceListener());

            BooleanSwitch boolSwitch = boolswitchFactory();

            boolSwitch.Print(TraceLevel.Info, "information");
            boolSwitch.Print(TraceLevel.Warning, "warning");
            boolSwitch.Print(TraceLevel.Error, "error");
        }

        public static void TestMain()
        {
            // CheckTraceSwitch(() => new TraceSwitch("manualSwitch", "none") { Level = TraceLevel.Error });
            // CheckTraceSwitch(() => new TraceSwitch("configedTraceSwitch", ""));
            // CheckBoolSwitch(()=>new BooleanSwitch("manualSwitch", "") { Enabled = true });
            CheckBoolSwitch(() => new BooleanSwitch("configedBoolSwitch", ""));
            // chekanote: although the switch's configuration is loaded from file, but in code, 
            // you can manually edit the configuration, and the manual configuration overwrites the configuration file 
            // CheckBoolSwitch(() => new BooleanSwitch("configedBoolSwitch", ""){Enabled = false});
        }
    }
}
